package com.lcz.service.impl;

import com.lcz.bean.Menu;
import com.lcz.bean.Role;
import com.lcz.bean.Users;
import com.lcz.dao.RoleDao;
import com.lcz.dao.UsersDao;
import com.lcz.dao.impl.RoleDaoImpl;
import com.lcz.dao.impl.UsersDaoImpl;
import com.lcz.service.UsersService;

import java.util.ArrayList;
import java.util.List;

public class UsersServiceImpl implements UsersService {
    private UsersDao usersDao = new UsersDaoImpl();
    private RoleDao roleDao = new RoleDaoImpl();

    @Override
    public Users login(String username, String password) {
        Users users = usersDao.login(username, password);
        if (users == null) {
            return null;
        }
        //根据角色id查询角色、菜单信息（role、menu、middle三表联查）
        Integer roleId = users.getRoleId();
        Role role = roleDao.findbyId(roleId);
        //需要对菜单进行分级
        List<Menu> menuList = role.getMenuList();
        List<Menu> newMenuList = new ArrayList();//保存分级以后的菜单
        for (Menu menu : menuList) {
            if (menu.getUpmenuId() == 0) {
                List<Menu> secondList = new ArrayList<>();
                for (Menu second : menuList) {
                    if (menu.getMenuId() == second.getUpmenuId()) {
                        secondList.add(second);
                    }
                }
                menu.setSecondMenuList(secondList);
                newMenuList.add(menu);
            }
        }
        role.setMenuList(newMenuList);
        users.setRole(role);
        return users;
    }

    @Override
    public List<Users> getUsersList(int pageIndex, int pageSize) {
        return usersDao.getUsersList(pageIndex, pageSize);
    }

    @Override
    public int total() {
        return usersDao.total();
    }
}
